import React, { useContext, useState } from 'react';
import {
  Row,
  Col,
  Card,
  Button,
  Modal,
  Form,
  Typography,
  Upload,
  message,
  Empty,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { RcFile } from 'antd/es/upload';
import { ServoDTO } from '../models/dtos/DTO';
import { SerialContext } from '../context/SerialContext';
import { convertFileToBase64 } from '../utils/base64';
import SerialBaudRateSelectView from '../views/SerialBaudRateSelectView';
import SerialDeviceSelectView from '../views/SerialDeviceSelectView';

import './ServoListComponent.css';
import { RouterUtils } from '../context/router';

interface Props {
  searchResults: { servo: ServoDTO }[];
  onServoUpgrade: () => void;
}

const DEFAULT_BAUDRATE = 115200;
const TEST_SERVO_ID = 0;

const TEST_DATA: { servo: ServoDTO }[] = [
  { servo: { baud: 115200, servo_id: 1, error_code: 0 } },
  { servo: { baud: 57600, servo_id: 2, error_code: 0 } },
  { servo: { baud: 115200, servo_id: 3, error_code: 1 } },
];

const ServoListComponent: React.FC<Props> = ({
                                               searchResults,
                                               onServoUpgrade,
                                             }) => {
  const ctx = useContext(SerialContext);

  if (!ctx) return null;

  const {
    serialState,
    servoModel,
    setServoModel,
    globalModel,
    serialState: { isSerialOpen, isSerialSearch, isSerialUpgrade },
  } = ctx;

  // 串口状态检查
  const checkSerialState = () => {
    if (!isSerialOpen) return message.error('请先连接串口');
    if (isSerialSearch) return message.error('请先停止搜索');
    if (isSerialUpgrade) return message.info('升级中，请稍后');
    return true;
  };

  // 跳转详情
  const handleNavigate = (servoId: number) => {
    if (checkSerialState() !== true) return;
    setServoModel({ ...servoModel, servo_id: servoId });
    RouterUtils.toServo(servoId);
  };

  return (
    <div className="servo-list-container">
      {searchResults.length === 0 ? (
        <Empty description="目前没有找到任何舵机，请稍后再试。" />
      ) : (
        <Row gutter={[16, 16]}>
          {searchResults.map(({ servo }, index) => (
            <Col xs={24} sm={12} md={8} lg={6} key={index}>
              <Card
                hoverable
                className="servo-card"
                onClick={() => handleNavigate(servo.servo_id)}
              >
                <p>
                  <strong>波特率:</strong> {servo.baud}
                </p>
                <p>
                  <strong>舵机ID:</strong> {servo.servo_id}
                </p>
                <p>
                  <strong>错误码:</strong> {servo.error_code}
                </p>
              </Card>
            </Col>
          ))}
        </Row>
      )}


    </div>
  );
};

export default ServoListComponent;
